#include "book-menu-convert.h"

#include <sstream>

#include "util/fs.h"
#include "util/logger/logger.h"


namespace book
{

static const char *title() {
    return "BookMenuConvert ";
}

BookMenuConvert::BookMenuConvert(const fs::path &destDir) {
    if (!fs::exists(destDir)) {
        std::ostringstream ss;
        ss << title() << "dest dir [" << destDir.generic_string() << "] not exist";
        throw DirCheckError(ss.str().c_str());
    }

    if (!fs::is_directory(destDir)) {
        std::ostringstream ss;
        ss << title() << "dest [" << destDir.generic_string() << "] is not dir";
        throw DirCheckError(ss.str().c_str());
    }

    const std::string path = (destDir / "a.bookmenu.html").lexically_normal().generic_string();
    out_.open(path, std::ios::binary);

    out_ << "<ul>";
}

BookMenuConvert::~BookMenuConvert() {
    out_ << "</ul>";
}

void BookMenuConvert::notifyEnterChapter(const UriPath &chapterUri, const IndexItem &indexItem) {
    LOGD << title() << "enter chapter " << chapterUri;
    out_ << "<li>";
    out_ << "<div class='menu-mid-level'>";
    out_ << indexItem.title();
    out_ << "</div>";
    out_ << "<ul>";
}

void BookMenuConvert::notifyLeaveChapter(const UriPath &chapterUri, const IndexItem &indexItem) {
    LOGD << title() << "leave chapter " << chapterUri;
    out_ << "</li>";
    out_ << "</ul>";
}

void BookMenuConvert::notifyMeetArticle(const UriPath &itemUri, const IndexItem &indexItem) {
    LOGD << title() << "meet article: " << itemUri;
    out_ << "<li>";
    out_ << "<a href='/book/abc-of-cpp" << itemUri << "'>";
    out_ << indexItem.title();
    out_ << "</a>";
    out_ << "</li>";
}

} // namespace book
